package com.dzu.medium;

/**
 * @author ZhaoDong
 * @date 2022/12/30 11:05
 * @description 394. 字符串解码
 */
public class Test394 {
    public static void main(String[] args) {
//        System.out.println(decodeString("3[a]2[bc]"));
//        System.out.println(decodeString("3[a2[c]]"));
//        System.out.println(decodeString("2[abc]3[cd]ef"));
//        System.out.println(decodeString("abc3[cd]xyz"));

        System.out.println(decodeString("3[z]2[2[y]pq4[2[jk]e1[f]]]ef"));
    }

    public static String decodeString(String s) {
        return dfs(s.toCharArray(), 0)[0];
    }

    private static String[] dfs(char[] chars, int index) {
        int num = 0;
        StringBuffer resp = new StringBuffer();
        for (int i = index; i < chars.length; i++) {
            char str = chars[i];
            if (Character.isDigit(str)) {
                num = num * 10 + (str - '0');
            } else {
                if (str == '[') {
                    String[] dfs = dfs(chars, i + 1);
                    i = Integer.parseInt(dfs[0]);
                    while (num > 0) {
                        resp.append(dfs[1]);
                        num--;
                    }

                } else if (str == ']') {
                    return new String[]{String.valueOf(i), resp.toString()};
                } else {
                    resp.append(str);
                }
            }
        }
        return new String[]{resp.toString()};
    }

}
